//
//  WBN_TV_PlayViewController.m
//  GoodManNews
//
//  Created by 王博男 on 16/1/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WBN_TV_PlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <MBProgressHUD.h>

#define PLAYURL @"v.ifeng.com/appData/video/singleVideo/3/01018e28-15d9-4a19-9b0d-d03430a9e8d3.js"

@interface WBN_TV_PlayViewController ()

@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, retain) AVPlayerLayer *playerLayer;

@property (nonatomic, assign) BOOL startBool;
@property (nonatomic, retain) UIButton *startB;
@property (nonatomic, retain) UIButton *pauseB;
@property (nonatomic, retain) UILabel *currentL;
@property (nonatomic, retain) UILabel *durationL;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UIProgressView *progressV;

@property (nonatomic, retain) AVPlayerViewController *playerVC;

@property (nonatomic, retain) UIButton *fullScreenB;
@property (nonatomic, assign) BOOL ifFullScreen;
@property (nonatomic, retain) UIView *bottomV;

@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, assign) NSInteger timerCount;
@property (nonatomic, retain) UITapGestureRecognizer *tapGR;
@property (nonatomic, retain) UIPanGestureRecognizer *panGR;

// 记录点击屏幕的点
@property (nonatomic, assign) CGFloat touchX;

@property (nonatomic, retain) UILabel *tempL;

@property (nonatomic, assign) BOOL pauseBool;

@property (nonatomic, retain) UIActivityIndicatorView *actIndV;


@end

@implementation WBN_TV_PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.progressV.progress = 0;
    
    NSURL *url = [NSURL URLWithString:@"http://funbox.w2.dwstatic.com/1/11/1520/118230-100-1431484187.mp4"];
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, 300);
    [self.view.layer addSublayer:self.playerLayer];
    //    self.playerLayer.backgroundColor = [[UIColor cyanColor] CGColor];
    
    
    [self createView];
    
    [self createHUD];
    
    self.currentL.text = @"00:00";
    self.durationL.text = @"00:00";
}

- (void)createView
{
    self.bottomV = [UIView new];
    self.bottomV.backgroundColor = [UIColor lightGrayColor];
    self.bottomV.alpha = 0.7;
    [self.view addSubview:self.bottomV];
    
    [self.bottomV mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(@265);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@30);
        
    }];
    
    
    self.startB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.startB setImage:[UIImage imageNamed:@"list_FM_playIcon_night@3x"] forState:UIControlStateNormal];
    [self.startB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.startB];
    
    
    self.startB.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2.0 - 25, 125, 50, 50);
    
    
    
//    self.progressV = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
//    [self.bottomV addSubview:self.progressV];
//    
    
    
    self.slider = [UISlider new];
    self.slider.backgroundColor = [UIColor clearColor];
    [self.slider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    [self.bottomV addSubview:self.slider];
    
    [self.slider mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.top.equalTo(self.bottomV);
        make.left.equalTo(@100);
        
    }];
    
    
//    [self.progressV mas_updateConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.equalTo(self.slider).offset(25);
//        make.left.equalTo(self.slider);
//        make.width.equalTo(self.slider);
//        make.height.equalTo(@3);
//        
//    }];
    
    
    
    self.currentL = [UILabel new];
    self.currentL.font = [UIFont systemFontOfSize:14];
    self.currentL.textColor = [UIColor whiteColor];
    self.currentL.textAlignment = NSTextAlignmentCenter;
    [self.bottomV addSubview:self.currentL];
    [self.currentL mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.bottom.equalTo(self.bottomV);
        make.width.equalTo(@50);
        make.right.equalTo(self.slider.mas_left);
        
    }];
    
    
    self.durationL = [UILabel new];
    self.durationL.font = [UIFont systemFontOfSize:14];
    self.durationL.textColor = [UIColor whiteColor];
    self.durationL.textAlignment = NSTextAlignmentCenter;
    [self.bottomV addSubview:self.durationL];
    [self.durationL mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.height.equalTo(self.bottomV);
        make.left.equalTo(self.slider.mas_right);
        make.width.equalTo(@50);
        
    }];
    
    
    self.fullScreenB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.fullScreenB setImage:[UIImage imageNamed:@"iconfont-quanping-2"] forState:UIControlStateNormal];
    [self.fullScreenB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomV addSubview:self.fullScreenB];
    
    self.fullScreenB.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 0, 50, 30);
    
    
    self.pauseB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.pauseB setImage:[UIImage imageNamed:@"iconfont-jiediankaishi"] forState:UIControlStateNormal];
    [self.pauseB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomV addSubview:self.pauseB];
    
    [self.pauseB mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.height.equalTo(self.bottomV);
        make.right.equalTo(self.currentL.mas_left);
        
    }];
    
    
    self.tempL = [UILabel new];
    self.tempL.backgroundColor = [UIColor blackColor];
    self.tempL.alpha = 0.4;
    self.tempL.textAlignment = NSTextAlignmentCenter;
    self.tempL.textColor = [UIColor whiteColor];
    [self.view addSubview:self.tempL];
    [self.tempL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(150);
        make.width.equalTo(@100);
        make.height.equalTo(@50);
        
    }];
    self.tempL.hidden = YES;
}

- (void)changeLayoutWithFull
{
    self.tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:self.tapGR];
    
    
    [self.bottomV mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset([UIScreen mainScreen].bounds.size.width - 50);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@50);
        
    }];
    
    
    self.playerLayer.frame = CGRectMake(0, 0, self.view.layer.frame.size.height, self.view.layer.frame.size.width);
    
    
    self.startB.frame = CGRectMake([UIScreen mainScreen].bounds.size.height / 2.0 - 50, [UIScreen mainScreen].bounds.size.width / 2.0 - 50, 100, 100);
    
    
    [self.slider mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.bottomV);
        make.left.equalTo(self.view).offset(100);
        make.right.equalTo(self.view).offset(-100);
        make.bottom.equalTo(self.bottomV).offset(-10);
        
    }];
    
    
    [self.currentL mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.height.equalTo(self.slider);
        make.left.equalTo(@50);
        
    }];
    
    
    [self.durationL mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.height.equalTo(self.slider);
        make.left.equalTo(self.slider.mas_right);
        make.right.equalTo(self.view).offset(-50);
        
    }];
    
    self.fullScreenB.frame = CGRectMake([UIScreen mainScreen].bounds.size.height - 50, 10, 50, 30);
    
    
    [self.pauseB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.slider);
        make.left.equalTo(self.view);
        make.right.equalTo(self.currentL.mas_left);
        make.bottom.equalTo(self.slider);
        
    }];
    
    
    [self createTimer];
    
}

- (void)createTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    self.timerCount = 0;
}

- (void)createPanGestureRecognizer
{
    self.panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.view addGestureRecognizer:self.panGR];
}

- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint point = [sender locationInView:self.view];
    CGFloat temp = point.x - self.touchX;
    
    self.slider.value = self.slider.value + (temp / [UIScreen mainScreen].bounds.size.height * (self.slider.maximumValue)) / 4.0;
    
    [self.player seekToTime:CMTimeMake(self.slider.value, 1)];
    
    
    self.tempL.hidden = NO;
    self.tempL.text = self.currentL.text;
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    self.touchX = point.x;
}


- (void)tapAction
{
    if (NO == self.bottomV.hidden) {
        
        [self.timer invalidate];
        self.bottomV.hidden = YES;
        
    } else {
        
        [self.timer invalidate];
        self.bottomV.hidden = NO;
        [self createTimer];
        
    }
}

- (void)timerAction
{
    self.timerCount++;
    
    if (self.timerCount > 3) {
        
        self.bottomV.hidden = YES;
        self.tempL.hidden = YES;
        
    }
}


- (void)changeLayout
{
    [self.bottomV mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(@265);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@30);
        
    }];
    
    
    self.playerLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, 300);
    
    
    self.startB.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2.0 - 25, 125, 50, 50);
    
    
    self.fullScreenB.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 0, 50, 30);
    
    
    [self.timer invalidate];
    [self.view removeGestureRecognizer:self.tapGR];
    
}

- (void)createHUD
{
    self.actIndV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.actIndV.center = CGPointMake(self.view.frame.size.width / 2, 150);
    self.actIndV.color = [UIColor blackColor];
    [self.view addSubview:self.actIndV];
}

- (void)buttonAction:(UIButton *)sender
{
    if (sender == self.startB) {
        
        self.startBool = YES;
        
        if (YES == self.startBool) {
            
            [self.player play];
            self.startB.hidden = YES;
            self.startBool = NO;
            
            [self.pauseB setImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
            self.pauseBool = NO;
            
            [self.actIndV startAnimating];
        }
        
        
    } else if (sender == self.fullScreenB) {
        
        self.ifFullScreen = !self.ifFullScreen;
        
        if (YES == self.ifFullScreen) {
            
            self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
            
            self.view.bounds = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width);
            
            [self.fullScreenB setImage:[UIImage imageNamed:@"iconfont-quitquanping-2"] forState:UIControlStateNormal];
            
            [self changeLayoutWithFull];
            
            [self createPanGestureRecognizer];
            
        } else if (NO == self.ifFullScreen) {
            
            self.view.transform = CGAffineTransformMakeRotation(0 * M_PI);
            
            self.view.bounds = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
            
            [self.fullScreenB setImage:[UIImage imageNamed:@"iconfont-quanping-2"] forState:UIControlStateNormal];
            
            [self changeLayout];
            
            [self.view removeGestureRecognizer:self.panGR];
            
        }
        
    } else if (sender == self.pauseB) {
        
        if (YES == self.startB.hidden) {
            
            [self.player pause];
            self.startB.hidden = NO;
            
            [self.pauseB setImage:[UIImage imageNamed:@"iconfont-jiediankaishi"] forState:UIControlStateNormal];
            self.pauseBool = YES;
            
        } else {
            
            [self.player play];
            self.startB.hidden = YES;
            self.startBool = NO;
            
            [self.pauseB setImage:[UIImage imageNamed:@"iconfont-iconfontzanting"] forState:UIControlStateNormal];
            self.pauseBool = NO;
            
        }
        
    }
}

- (void)sliderAction
{
    [self.player seekToTime:CMTimeMake(self.slider.value, 1)];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerItemStatusReadyToPlay) {
//            NSLog(@"可以开始了");
            
            //            self.startB.enabled = YES;
            
            //总时间
            CMTime duration = self.playerItem.duration;
            //            NSLog(@"总时间%f", CMTimeGetSeconds(duration));
            
            //总秒数
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;
            self.slider.maximumValue = totalSecond;
            //            NSLog(@"总秒数%lf",totalSecond);
            
            
            self.durationL.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)totalSecond / 60, (NSInteger)totalSecond % 60];
            
            
            if (YES == self.startBool) {
                [self.player play];
            }
            
            
            //此处可以设置时间条 进行监听
            [self monitoringPlayback:playerItem];
            
        }else if ([playerItem status] == AVPlayerItemStatusFailed) {
            NSLog(@"播放失败");
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]) {
        //计算缓存进度
        NSTimeInterval timeInterval = [self availableDuration];
//        NSLog(@"缓冲进度%f", timeInterval);
        
        [self.progressV setProgress:timeInterval / self.slider.maximumValue animated:YES];
    }
    
}

//计算缓存进度
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    //缓冲开始
    float startSecond =  CMTimeGetSeconds(timeRange.start);
    //    NSLog(@"startSecond+++++  %f", startSecond);
    //缓冲总
    float durationSecond = CMTimeGetSeconds(timeRange.duration);
    //    NSLog(@"durationSecond+++++  %f", durationSecond);
    //计算缓冲中总进度
    NSTimeInterval result = startSecond + durationSecond;
    
    
    if (NO == self.pauseBool && YES == self.startB.hidden) {
        
        [self.player play];
    }
    
    
    return result;
}
//播放后监听
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:NULL usingBlock:^(CMTime time) {
        
        CGFloat currentSecond = playerItem.currentTime.value / playerItem.currentTime.timescale;
        
        //        NSLog(@"当前播放时间:%lf", currentSecond);
        
        
        self.currentL.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)currentSecond / 60, (NSInteger)currentSecond % 60];
        
        
        if (self.slider.value != currentSecond) {
            [self.actIndV stopAnimating];
        }
        
        
        [self.slider setValue:currentSecond animated:YES];
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
